<template>
  <div class="mod-config">
    <el-form>
      <el-form-item>
        <el-button size="mini" v-if="isAuth('goods:goodsware:save')" type="primary" @click="addOrUpdateHandle()">新增
        </el-button>
        <el-button size="mini" v-if="isAuth('goods:goodsware:delete')" type="danger" @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input size="mini" v-model="dataForm.key" placeholder="参数名" clearable @clear="getDataList()" @blur="getDataList()" ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="success" @click="getDataList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border size="mini" v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      style="width: 100%;"  @cell-dblclick="tableDbEdit"
      :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column type="index" header-align="center" align="center" label="">
      </el-table-column>
      <el-table-column prop="wareName" header-align="center" align="center" label="仓库名称">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.wareName" v-if="showInput == `wareName${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "wareName", scope.row.wareName)' v-focus>
          </el-input>
          <span v-else>{{scope.row.wareName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="wareCode" header-align="center" align="center" label="仓库编号">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.wareCode" v-if="showInput == `wareCode${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "wareCode", scope.row.wareCode)' v-focus>
          </el-input>
          <span v-else>{{scope.row.wareCode}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch size="mini" v-model="scope.row.status" @change="saveHandle(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="updateTime" header-align="center" align="center" label="修改时间">
      </el-table-column>
      <el-table-column prop="createUsername" header-align="center" align="center" label="创建人">
      </el-table-column>
      <el-table-column prop="updateUsername" header-align="center" align="center" label="修改人">
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
        <template slot-scope="scope">
          <span v-html="scope.row.remark"></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="saveHandle(scope.row)">保存</el-button>
          <el-button size="mini" type="text" @click="addOrUpdateHandle(scope.row.wareId)">修改</el-button>
          <el-button size="mini" type="text" @click="deleteHandle(scope.row.wareId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './goodsware-add-or-update'
  export default {
    data() {
      return {
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        showInput: "",
        oldData: {},
        currentData: {},
      }
    },
    components: {
      AddOrUpdate
    },
    activated() {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/goods/goodsware/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount

            this.dataList.forEach(item => {
              item.status = item.status == 1 ? true : false
            })

          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(wareId) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(wareId)
        })
      },
      // 删除
      deleteHandle(wareId) {
        var ids = wareId ? [wareId] : this.dataListSelections.map(item => {
          return item.wareId
        })
        this.$confirm(`确定对[wareId=${ids.join(',')}]进行[${wareId ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/goods/goodsware/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 当input失去光标后进行的操作
      async blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          if (value === true) {
            row[name] = 1
          } else if (value === false) {
            row[name] = 0
          }
        }
        this.showInput = ""
        this.currentData = row
      },
      async saveHandle(row) {
        row.status = row.status ? 1 : 0
        const res = await this.$http({
          url: `/goods/goodsware/update`,
          method: 'post',
          data: this.$http.adornData(row)
        });
        let data = res.data
        if (data && data.code !== 0) {
          row.status = !row.status;
          return this.$message.error('修改失败!');
        }
        this.$message.success('更新成功！');
        this.getDataList();
      },
      tableDbEdit(row, column, event) {
        this.showInput = column.property + row.supplierId
        this.oldData[column.property] = row[column.property]
      }
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
  }
</script>
